//
//  CustomRefreshHeader.m
//  Qianbancaifu
//
//  Created by uju_macmini on 16/7/8.
//  Copyright © 2016年 SYLH. All rights reserved.
//

#import "CustomRefreshHeader.h"

#define KSucessOrFailDelayTime 0.8f
#define KImageLabelGapX  6.f
#define KIMAGE_WH 24.f
#define KRefreshSuccessText KNSLocal(@"refreshSuccess")
#define KRefreshFailText KNSLocal(@"refreshFail")


@interface CustomRefreshHeader()
{
    UIImage *pa_successImage;
    UIImage *pa_failImage;
    NSInteger parefreshStatus;
    CABasicAnimation *faderAnimation;
    CALayer *instanceLayer;
    CAReplicatorLayer *replicatorLayer;
}
@end
@implementation CustomRefreshHeader
-(UIImageView *)customImageView
{
    if (!_customImageView) {
        UIImageView *gifView = [[UIImageView alloc] init];
        pa_successImage=[UIImage imageNamed:@"Refresh_sucess"];
        pa_failImage=[UIImage imageNamed:@"Refresh_fail"];
        _pca_statusLabel=[[UILabel alloc] init];
        _pca_statusLabel.textColor=[UIColor colorWithHex:0x262E38 alpha:1];
        _pca_statusLabel.font = PFR_FONT(14);
        [self addSubview:_pca_statusLabel];
        _pca_statusImageView=[[UIImageView alloc] init];
        _pca_statusImageView.image=pa_successImage;
        [self addSubview:_pca_statusImageView];
        _pca_statusImageView.hidden=YES;
        _pca_statusLabel.hidden=YES;
        parefreshStatus=0;
        replicatorLayer=[[CAReplicatorLayer alloc] init];
        replicatorLayer.instanceColor =[UIColor grayColor].CGColor;
        [gifView.layer addSublayer:replicatorLayer];
        instanceLayer=[CALayer layer];
        instanceLayer.backgroundColor =[UIColor whiteColor].CGColor;
        instanceLayer.cornerRadius=1;
        [replicatorLayer addSublayer:instanceLayer];
        [self addSubview:_customImageView = gifView];
    }
    return _customImageView;
}
#pragma mark - 实现父类的方法
- (void)setPullingPercent:(CGFloat)pullingPercent
{
    [super setPullingPercent:pullingPercent];
}
-(void)scrollViewPanStateDidChange:(NSDictionary *)change
{
    [super scrollViewPanStateDidChange:change];
    if (_scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan) {// 手松开
        self.pca_statusImageView.hidden=YES;
        self.pca_statusLabel.hidden=YES;
        self.customImageView.hidden=NO;
    }
}
#pragma mark --设置不同状态下执行方法
-(void)setState:(MJRefreshState)state
{
    MJRefreshCheckState
    if (state == MJRefreshStateRefreshing) {
        [self beiginAnimation];
    } else if (state == MJRefreshStateIdle) {
        [self removeFadeAnimationIfExist];
    }
}

#pragma mark --配置界面
- (void)placeSubviews
{
    [super placeSubviews];
    if (parefreshStatus==1) {
        self.pca_statusLabel.text=KRefreshSuccessText;
    }else
    {
        self.pca_statusLabel.text=KRefreshFailText;
    }
    CGSize actrualSize=[self.pca_statusLabel sizeThatFits:self.bounds.size];
    if (parefreshStatus==1) {
        self.pca_statusImageView.frame=CGRectMake(CGRectGetWidth(self.bounds)/2-(actrualSize.width+pa_successImage.size.width+KImageLabelGapX)/2, CGRectGetHeight(self.bounds)/2-pa_successImage.size.height/2, pa_successImage.size.width, pa_successImage.size.height);
        self.pca_statusImageView.image=pa_successImage;
    }else
    {
        self.pca_statusImageView.frame=CGRectMake(CGRectGetWidth(self.bounds)/2-(actrualSize.width+pa_failImage.size.width+KImageLabelGapX)/2, CGRectGetHeight(self.bounds)/2-pa_failImage.size.height/2, pa_failImage.size.width, pa_failImage.size.height);
        self.pca_statusImageView.image=pa_failImage;
    }
    self.pca_statusLabel.frame=CGRectMake(CGRectGetMaxX(self.pca_statusImageView.frame)+KImageLabelGapX, CGRectGetMidY(self.bounds)-actrualSize.height/2, actrualSize.width, actrualSize.height);
    self.customImageView.frame = CGRectMake(CGRectGetMidX(self.bounds)-KIMAGE_WH/2, CGRectGetMidY(self.bounds)-KIMAGE_WH/2, KIMAGE_WH, KIMAGE_WH);
    replicatorLayer.frame=self.customImageView.bounds;
    CGFloat layerWidth= 3;
    CGFloat midX = CGRectGetMidX(self.customImageView.bounds) - layerWidth / 2;
    instanceLayer.frame=CGRectMake(midX, 0.0, layerWidth, layerWidth*2.5);
    replicatorLayer.instanceDelay =1.0 / 8;
    replicatorLayer.instanceTransform = CATransform3DMakeRotation(M_PI * 2.0/8, 0.0, 0.0, 1.0);
}
#pragma mark --坐标位置变化监测
-(void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
    [super scrollViewContentOffsetDidChange:change];
    CGPoint old = [change[@"old"] CGPointValue];
    CGPoint new = [change[@"new"] CGPointValue];
    if (new.y < old.y)
    {
        //正在下拉刷新
        if (self.state!=MJRefreshStateRefreshing) {
            if (_scrollView.mj_h>(-new.y)) {
                if (_scrollView.mj_h>(-new.y)) {
                    [self removeFadeAnimationIfExist];
                }
            }
        }else
        {
            replicatorLayer.instanceCount = 8;
        }
    }else if(new.y > old.y)
    {
        if (self.state!=MJRefreshStateRefreshing) {
            if (_scrollView.mj_h>(-new.y)) {
                [self removeFadeAnimationIfExist];
            }
        }
    }
}
-(void)removeFadeAnimationIfExist
{
    
    replicatorLayer.instanceCount = ((int)(self.pullingPercent*8)>=8)?(8):(int)(self.pullingPercent*8);
    if(faderAnimation != nil) {
        instanceLayer.opacity = 1.0;
        [instanceLayer removeAnimationForKey:@"fader"];
    }
}
-(void)beiginAnimation
{
    if (faderAnimation==nil) {
        faderAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
    }
    faderAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    faderAnimation.toValue = [NSNumber numberWithFloat:0.0];
    faderAnimation.duration = 1;
    faderAnimation.repeatCount = NSIntegerMax;
    instanceLayer.opacity = 0.0;
    [instanceLayer addAnimation:faderAnimation forKey:@"fader"];
}
-(void)endRefreshingSuccess
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.pca_statusImageView.hidden=NO;
        self.pca_statusLabel.hidden=NO;
        self.customImageView.hidden=YES;
        parefreshStatus=1;
        [self placeSubviews];
        [self performSelector:@selector(endRefreshing) withObject:nil afterDelay:KSucessOrFailDelayTime];
    });
}
-(void)endRefreshingFail
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.pca_statusImageView.hidden=NO;
        self.pca_statusLabel.hidden=NO;
        self.customImageView.hidden=YES;
        parefreshStatus=2;
        [self placeSubviews];
        [self performSelector:@selector(endRefreshing) withObject:nil afterDelay:KSucessOrFailDelayTime];
    });
}
-(void)beginRefreshing
{
    self.pca_statusImageView.hidden=YES;
    self.pca_statusLabel.hidden=YES;
    self.customImageView.hidden=NO;
    [super beginRefreshing];
}
-(void)endRefreshing
{
    [super endRefreshing];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
